﻿using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Assist;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using HYView;

namespace YJKArch.ElementCollisionChecking
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class CmdCollisionChecking : IExternalCommand
	{
		[DllImport("User32.dll")]
		private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			CmdViewType types = (CmdViewType)127;
			if (SwitchView.SetUsableView(types, commandData) != Autodesk.Revit.UI.Result.Succeeded)
			{
				return Autodesk.Revit.UI.Result.Failed;
			}
			Result result;
			try
			{
				if (commandData == null)
				{
					throw new System.ArgumentNullException("commandData");
				}
				if (CmdCollisionChecking.FindWindow(null, "构件重叠检查") != IntPtr.Zero)
				{
					result = Autodesk.Revit.UI.Result.Cancelled;
				}
				else
				{
					if (CmdCollisionChecking._hWndRevit == null)
					{
						CmdCollisionChecking._hWndRevit = new WindowHandle(Process.GetCurrentProcess().MainWindowHandle);
					}
					new CollisionCheckingManager(commandData).RunCollisionChecking();
					result = Autodesk.Revit.UI.Result.Succeeded;
				}
			}
			catch (Exception ex)
			{
				message = ex.Message;
				result = Autodesk.Revit.UI.Result.Failed;
			}
			return result;
		}

		public static WindowHandle _hWndRevit;
	}
}
